package com.ruoyi.file.service.impl;

import com.ruoyi.common.core.domain.ResultResponse;
import com.ruoyi.file.service.IFtpFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
public class FtpFileServiceImpl implements IFtpFileService {

    @Value("${ftp.host}")
    public String host;
    @Value("${ftp.port}")
    public Integer port;
    @Value("${ftp.username}")
    public String username;
    @Value("${ftp.password}")
    public String password;

    @Override
    public ResultResponse uploadFtpFile(String elativefilePath, String fileName, InputStream inputStream) throws IOException {
        ResultResponse resultResponse = new ResultResponse();
        FTPClient ftpClient = null;
        try{
            ftpClient = getFTPClient();
            if(ftpClient == null){
                log.info("连接ftp服务失败...");
                resultResponse.setShuCode("error");
                resultResponse.setMsg("连接ftp服务失败...");
                inputStream.close();
                return resultResponse;
            }
            //ftpClient切换到目标文件夹
            changeWorkingDir(elativefilePath, ftpClient);

            //上传文件
            if(ftpClient.storeFile(fileName, inputStream)){
                log.info("上传文件成功...");
            }else{
                log.info("上传文件失败...");
                resultResponse.setShuCode("error");
                resultResponse.setMsg("上传文件失败...");
            }
        }catch (IOException e){
            resultResponse.setShuCode("error");
            resultResponse.setMsg("上传文件操作失败...");
        }finally {
            inputStream.close();
            ftpClient.logout();
        }
        return resultResponse;
    }

    //连接获取ftpClient
    public FTPClient getFTPClient() throws IOException {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.connect(host, port);
        if (!ftpClient.login(username, password)) {
            log.info("connected fail...");
            return null;
        }
        //FTPClient.BINARY_FILE_TYPE=2 标识文件为二进制类型
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();
            log.info("FTP server refused connection...");
            return null;
        }
        return ftpClient;
    }

    //切换到指定文件夹中，如果不存在就创建
    public void changeWorkingDir(String elativefilePath, FTPClient ftpClient) throws IOException {
        if(!ftpClient.changeWorkingDirectory(elativefilePath)){
            //创建目录
            String[] dirs = elativefilePath.split("/");
            String tempPath = "";
            for (String dir: dirs) {
                if(null == dir || "".equals(dir)){
                    //跳出本地循环，进入下一次循环
                    continue;
                }
                tempPath += "/" + dir;
                if(!ftpClient.changeWorkingDirectory(tempPath)){
                    if(!ftpClient.makeDirectory(tempPath)){
                        log.info("无法创建文件夹...");
                    }else{
                        ftpClient.changeWorkingDirectory(tempPath);
                    }
                }
            }
        }
    }
}
